#include <iostream>
using namespace std;

// 赋值运算符重载
class Person
{
public:
    int* age;
    
    Person(int Age)
    {
        age = new int(Age);
    }

    ~Person()
    {
        if (age != NULL)
        {
            delete age;
        }
    }

    // 重载，赋值运算符
    Person& operator=(Person& p)
    {
        // 编译器提供浅拷贝：this->age = p.age;

        // 应该先判断是否有属性在堆区，如果有，则先释放
        if (age != NULL)
        {
            delete age;
        }
        age = new int(*p.age);// 深拷贝操作
        
        // 返回对象本身
        return *this;
    }
      
};

void test1()
{
    Person p1(18);
    cout << "p1的年龄为：" << *p1.age << endl;

    Person p2(20);
    cout << "p2的年龄为：" << *p2.age << endl;

    
    cout << "------赋值后-------" << endl;
    p2 = p1; // 赋值运算
    cout << "p1的年龄为：" << *p1.age << endl;
    cout << "p2的年龄为：" << *p2.age << endl;

    
    cout << "------连续赋值后-------" << endl;
    Person p3(50);
    p1 = p2 = p3; // 赋值操作
    cout << "p1的年龄为：" << *p1.age << endl;
    cout << "p2的年龄为：" << *p2.age << endl;
    cout << "p3的年龄为：" << *p3.age << endl;
    
    Person p4 = p3;// 拷贝构造
    
}

int main()
{
    test1();
    return 0;
}